package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listStatus(AuthDTO dto) {
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //参数检查
        dto.checkParam();
        //2 :条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
                if(dto.getStatus()!=null){
                   wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
                }
        IPage<ApUserRealname> resultPage = page(page, wrapper);
                //返回结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),resultPage.getTotal(),resultPage.getRecords());
    }

    /**
     * 根据状态进行审核
     * @param dto
     * @param status     1:待审核 2: 审核失败   9:审核成功
     * @return
     */
   @Autowired
    ApUserMapper apUserMapper;
   @Autowired
   WemediaFeign wemediaFeign;
   @Autowired
   ArticleFeign articleFeign;
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)  //开启全局事务
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1: 参数检查
        if(dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2:查询当前认证用户是否在APP端有当前用户
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId, dto.getId())
                .eq(ApUserRealname::getStatus, 1));  //审核未通过的用户
        if(apUserRealname==null){
            log.error("用户不存在",dto.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserRealname.getUserId()));
        if(apUser==null){
            log.error("用户不存在",dto.getId(),apUserRealname.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3:更正认证用户信息
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        apUserRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //4: 认证状态如果为9 通过
        if(AdminConstants.PASS_AUTH.equals(status)){
            //4.1 创建自媒体账户
            WmUser wmUser =creatWmUser(dto,apUser);
            //创建作者信息
            creatApAuthor(wmUser);
        }
        //5: 更新APP用户状态
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        //6:返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建作者信息
     * @param wmUser
     */
    private void creatApAuthor(WmUser wmUser) {
        //1: 检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(apAuthorResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //2: 检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if(apAuthor!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在");
        }
        //3:添加作者信息
        apAuthor=new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);  //自媒体人类型
        apAuthor.setUserId(wmUser.getId());  //自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        //4: 结果失败  抛出异常   TODO:看不懂  getCode()!=0为什么错误????????
        if(result.getCode()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }

    }


    /**
     * 创建自媒体账号
     * @param dto
     * @param apUser   APP端用户
     * @return
     */
    private WmUser creatWmUser( AuthDTO dto, ApUser apUser) {
        //1: 查询自媒体账号是否存在(APP端用户和自媒体密码一致)
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if(wmUserResult.getCode().intValue()!=0){    //TODO  wmUserResult.getCode().intValue()!=0?????????
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser = wmUserResult.getData();
        if(wmUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户信息已存在");
        }
        wmUser=new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  //盐
        wmUser.setPassword(apUser.getPassword()); //密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0);  //个人类型
        wmUser.setApUserId(apUser.getId());
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue() !=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }
}
